<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>17-模型动画</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }

      html,
      body {
        width: 100%;
        height: 100%;
        overflow: hidden;
      }
      .process {
        position: absolute;
        top: 0;
        left: 0;
        font-size: 20px;
      }
      .color-selector {
        position: absolute;
        top: 0;
        right: 20px;
      }
    </style>
  </head>

  <body>
    <p class="process"></p>
    <div class="color-selector">
      <input type="color" class="input" />
    </div>
    <script type="module">
      // 引入three.js
      import * as THREE from "three";
      //引入物理引擎cannon
      import * as Cannon from "cannon";
      import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
      import { GLTFLoader } from "three/three/examples/jsm/loaders/GLTFLoader.js";
      import { OBJLoader } from "three/three/examples/jsm/loaders/OBJLoader.js";
      import { FBXLoader } from "three/three/examples/jsm/loaders/FBXLoader.js";

      //创建场景
      const scene = new THREE.Scene();

      //创建相机
      const camera = new THREE.PerspectiveCamera(
        45,
        window.innerWidth / window.innerHeight,
        0.1,
        1000
      );
      //设置相机位置
      camera.position.set(0, 0.5, -3.5); //统一设置
      //设置相机朝向点位
      camera.lookAt(0, 0, 0);
      scene.add(camera);

      //创建渲染器
      const renderer = new THREE.WebGLRenderer({
        antialias: true, //减少边缘齿轮
      });
      renderer.setSize(window.innerWidth, window.innerHeight);
      renderer.shadowMap.enabled = true; //开启阴影投射
      document.body.appendChild(renderer.domElement);

      const ambientlLight = new THREE.AmbientlLight(0xffffff, 1);
      const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
      scene.add(ambientlLight, directionalLight);

      //控制插件
      const controls = new OrbitControls(camera, renderer.domElement);
      controls.enableDamping = true; //开启惯性,需要和update方法配合使用
      controls.addEventListener("change", () => {});
      const process = document.querySelector(".process");

      let chair;
      const input = document.querySelector(".input");
      input.addEventListener("input", (event) => {
        if (chair) {
          chair.material.color.set(event.target.value);
        }
      });

      //加载模型
      const gltfLoader = new GLTFLoader();
      let mixer, idleAction, runAction, currentAction;
      gltfLoader.load(
        "../models/Soldier.glb",
        (gltf) => {
          chair = gltf.scene.children[0];
          const model = gltf.scene;
          const animations = gltf.animations;
          mixer = new THREE.AnimationMixer(model);
          const runClip = animations.find((clip) => clip.name === "Run");
          const idleClip = animations.find((clip) => clip.name === "Idle");
          if (runClip && idleClip) {
            runAction = mixer.clipAction(runClip);
            idleAction = mixer.clipAction(idleClip);
            idleAction.play();
            currentAction = idleAction;
          }
          if (idleClip) {
          }
          scene.add(model);
        },
        (xhr) => {
          const percent = (xhr.loaded / xhr.toal) * 100;
          process.textContent = `${Math.round(percent, 2)}%`;
        },
        (err) => {
          console.log(err);
        }
      );

      window.addEventListener("keydown", (event) => {
        if (event.code == "keyW") {
          if (runAction && currentAction !== runAction) {
            currentAction.fadeOut(0.5); //结束当前动作（站立）
            runAction.reset().fadeIn(0.5).play(); //开启跑动
            currentAction = runAction; //将当前动作切换成跑动
          }
        }
      });
      window.addEventListener("keyup", (event) => {
        if (event.code == "keyW") {
          if (idleAction && currentAction !== idleAction) {
            currentAction.fadeOut(0.5); //结束当前动作（跑动）
            idleAction.reset().fadeIn(0.5).play(); //开启站立
            currentAction = runAction;
          }
        }
      });

      const fbxLoader = new FBXLoader();
      fbxLoader.load("../models/Samba Dancing.fbx", (fbx) => {
        fbx.position.set(-2, 0, 0);
        fbx.scale.set(0.01, 0.01, 0.01);
        scene.add(fbx);
      });

      //动画函数
      const clock = new THREE.Clock();
      function animate() {
        const elapsedTime = clock.getDelta();
        if (mixer) {
          mixer.update(elapsedTime); //人物跑动
        }
        controls.update();
        renderer.render(scene, camera);
        requestAnimationFrame(animate);
      }
      animate();
    </script>
  </body>
</html>
